#include <string.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "led.h"

#define SYS_RUN_LED_PIN                     5
#define LED_ON                              IOT_GPIO_VALUE0
#define LED_OFF                             IOT_GPIO_VALUE1
static int g_ledInitState = 0;

int LedFlash(int mode, int time)
{
    if (!g_ledInitState) {
        int ret;
        ret = IoTGpioInit(SYS_RUN_LED_PIN);
        if (ret != 0) {
            return ret;
        }
        ret = IoTGpioSetDir(SYS_RUN_LED_PIN, IOT_GPIO_DIR_OUT);
        if (ret != 0) {
            return ret;
        }
        g_ledInitState = 1;
    }
    
    if(mode == LED_OFF_MODE) {
        IoTGpioSetOutputVal(SYS_RUN_LED_PIN, LED_OFF);
    } else if(mode == LED_ON_MODE) {
        IoTGpioSetOutputVal(SYS_RUN_LED_PIN, LED_ON);
    } else if(mode == LED_FLASH_MODE) {
        if (time <= 0) {
            printf("Invalid value\r\n");
            return -1;
        }

        int led_state = LED_OFF;
        int start_time = osKernelGetSysTimerCount();
        while (1) {
            int current_time = osKernelGetSysTimerCount();
            int elapsed_time = (current_time - start_time);
            if (elapsed_time >= time*1000) {
                break;
            }

            if (led_state == LED_OFF) {
                IoTGpioSetOutputVal(SYS_RUN_LED_PIN, LED_ON);
                led_state = LED_ON;
            } else {
                IoTGpioSetOutputVal(SYS_RUN_LED_PIN, LED_OFF);
                led_state = LED_OFF;
            }

            osDelay(200);
        }

        IoTGpioSetOutputVal(SYS_RUN_LED_PIN, LED_OFF);
        }
}